package com.miyake.client.datamanage;

import java.util.ArrayList;
import java.util.List;

import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.DialogBox;
import com.miyake.client.DataService;
import com.miyake.client.datamanage.plugin.MyAnalysisPluginChooser;
import com.miyake.client.tools.ShowDialog;
import com.miyake.client.tools.WaitPopup;

public class DoAnalysis {
	private List<String> nodes = new ArrayList<String>();
	private Integer columnCount;
	private NodeUpdateHandler updateHandler;
	
	public DoAnalysis(String nodeKey, Integer columnCount, NodeUpdateHandler updateHandler) {
		nodes.add(nodeKey);
		this.columnCount = columnCount;
		this.updateHandler = updateHandler;
		initialize();
	}
	
	public DoAnalysis(List<String> nodeKeys, Integer columnCount, NodeUpdateHandler updateHandler) {
		this.nodes = nodeKeys;
		this.columnCount = columnCount;
		this.updateHandler = updateHandler;
		initialize();
	}
	
	protected void initialize() {
		final MyAnalysisPluginChooser dlg = new MyAnalysisPluginChooser() {
			@Override
			protected String getKey() {
				return nodes.get(0);
			}

			@Override
			protected Integer getColumnCount() {
				return columnCount;
			}
		};
		new ShowDialog() {
			@Override
			protected void onOK(String text) {
				doAnalysis(dlg.getPluginKey(), dlg.getSetup(), dlg.getSelectedColumn());
			}

			@Override
			protected DialogBox getDialogBox() {
				return dlg;
			}
		};
	}
	
	private void doAnalysis(String pluginKey, AnalysisSetup setup, Integer column) {
		WaitPopup.showPopup(nodes.size());
		for (final String node : nodes) {
			DataService.Util.getInstance().doAnalysis(node, pluginKey, setup, column, new AsyncCallback<String>(){
	
				@Override
				public void onFailure(Throwable caught) {
					Window.alert(caught.getMessage());
				}
	
				@Override
				public void onSuccess(String result) {
					WaitPopup.hidePopup();
					if (!WaitPopup.isPopupVisible()) {
						updateHandler.onNodeAdd(node);
					}
				}
			});
		}
	}
}
